﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.NetworkInformation;
using System.Net;
using System.ComponentModel;
using System.Threading;
//using System.Windows.Forms;

namespace BussinesLayer
{
    public static class InternetConnection
    {
        static BackgroundWorker worker = new BackgroundWorker();

        public static bool IsConnected()
        {
            Uri Url = new Uri("http://www.microsoft.com");

            WebRequest WebReq;
            WebResponse Resp;
            WebReq = System.Net.WebRequest.Create(Url);
            Thread.Sleep(60000);

            try
            {
                Resp = WebReq.GetResponse();
                Resp.Close();
                WebReq = null;
                return true;
            }

            catch
            {
                WebReq = null;
                return false;
            }
        }

        public static void BeginInternetConnectionCheck()
        {
            worker.WorkerReportsProgress = false;
            worker.WorkerSupportsCancellation = false;
            worker.DoWork += new DoWorkEventHandler(DoCheckConnectionWork);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CheckConnectionCompleted);

            worker.RunWorkerAsync();
        }

        private static void DoCheckConnectionWork(object sender, DoWorkEventArgs e)
        {
            e.Result = IsConnected();
        }

        private static void CheckConnectionCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if ((bool)e.Result)
            {
                //MessageBox.Show("Connected");
                
            }
            worker.RunWorkerAsync();
        }
    }
}
